const votesProxy = require('../proxy/votes')

exports.fetchVotesInTeam = async function(req, res, next) {
  try {
    const { teamId } = req.user
    let { page, per_page } = req.query
    if (!page || page < 1) page = 1
    if (!per_page || per_page < 1) per_page = 50
    const items = await votesProxy.getAllVoteInTeam(teamId, (page - 1) * per_page, per_page * 1)
    const total = await votesProxy.countVotes(teamId)
    res.json({ items, total })
  } catch (err) {
    next(err)
  }
}

exports.createVote = async function(req, res, next) {
  if (!req.user.roles.some(v => v === 'admin' || v === 'vote')) {
    return res.status(403).end()
  }
  try {
    const { title, type, secret, options } = req.body
    const vote = await votesProxy.createVoteInTeam(title, type, secret, options, req.user.teamId)
    res.json({ ...vote.toObject() })
  } catch (err) {
    next(err)
  }
}

exports.fetchVote = async function(req, res, next) {
  try {
    const vote = await votesProxy.fetchVoteInTeam(req.params.voteId, req.user.teamId)
    if (!vote) return res.sendStatus(204).end()
    else res.json({ ...vote.toObject() })
  } catch (err) {
    next(err)
  }
}

exports.fetchBucket = async function(req, res, next) {
  try {
    const bucket = await votesProxy.fetchBucket(req.params.voteId, req.user.userId)
    if (!bucket) res.sendStatus(204).end()
    else res.json({ ...bucket.toObject() })
  } catch (err) {
    next(err)
  }
}

exports.createBucket = async function(req, res, next) {
  try {
    const { voteId } = req.params
    const bucket = await votesProxy.createBucketForVote(voteId, req.user.userId, req.body.data)
    res.json({ bucket })
  } catch (err) {
    next(err)
  }
}

exports.fetchVoteResult = async function(req, res, next) {
  try {
    const dataSet = await votesProxy.fetchBucketForVote(req.params.voteId)
    res.json({ dataSet })
  } catch (err) {
    next(err)
  }
}

exports.fetchAllVoteBucket = async function(req, res, next) {
  if (!req.user.roles.some(v => v === 'admin' || v === 'vote')) {
    return res.status(403).end()
  }
  try {
    const data = await votesProxy.fetchAllBucketsForVote(req.params.voteId)
    // console.log(data)
    res.json({ items: data })
  } catch (err) {
    next(err)
  }
}
